package br.com.rumus.dao.seguranca;

import java.util.List;

import javax.persistence.Query;

import br.com.rumus.dao.DAOGenerico;
import br.com.rumus.dominio.seguranca.Papel;
import br.com.rumus.dominio.seguranca.Usuario;

public class UsuarioDAO extends DAOGenerico<Usuario, Long>{

	public Usuario buscar(String nome){
		return (Usuario) getEntityManager().createQuery(" select u " +
														"   from Usuario u " +
														"  where u.nome = :nome ")
														.setParameter("nome",nome) 
														.getSingleResult();
	}
	
	public boolean autenticar( String nome, String senha ){
		Long qtd = (Long) getEntityManager().createQuery(" select count(u) " +
														 "   from Usuario u " +
														 "  where u.nome  = :nome " +
														 "    and u.senha = :senha")
														 .setParameter("nome",nome) 
														 .setParameter("senha",senha)
														 .getSingleResult();
		return (qtd>0);
	}

	@SuppressWarnings("unchecked")
	public List<Usuario> pesquisar( Usuario usuario, int registro, int quantidade ){
		StringBuilder JPQL = new StringBuilder( "select u from Usuario u where ( u.nome like :nome or :nome is null )" );
		Query query = getEntityManager().createQuery(JPQL.toString());
		query.setParameter("nome", (usuario!=null&&usuario.getNome()!=null&&!usuario.getNome().equals(""))?usuario.getNome():null);
		query.setFirstResult(registro);
		query.setMaxResults(quantidade);
		return query.getResultList();
	}

	public int pesquisar( Usuario usuario ){
		StringBuilder JPQL = new StringBuilder( "select count(*) from Usuario u where ( u.nome like :nome or :nome is null )" );
		Query query = getEntityManager().createQuery(JPQL.toString());
		query.setParameter("nome", (usuario!=null&&usuario.getNome()!=null&&!usuario.getNome().equals(""))?usuario.getNome():null);
        Number registros = null;
        registros = (Number) query.getSingleResult();
        return registros == null ? 0 : registros.intValue();
	}	
	
}